package RSS.reader;

import RSS.buffer.NewsBuffer;
import RSS.writer.NewsWriterTask;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: gitee4_socket
 * @description:
 * @author: zy
 * @create: 2024-07-24 17:02
 */
public class NewsSystem implements Runnable {
    private String sourcesPath;   //sources.txt文件的地址
    private ScheduledThreadPoolExecutor   executor;  //定时调度的线程池
    private NewsBuffer buffer;

    private Logger log= Logger.getLogger(   NewsSystem.class.getName() );

    public NewsSystem(String sourcesPath) {
        this.sourcesPath = sourcesPath;
        this.executor=new ScheduledThreadPoolExecutor(    Runtime.getRuntime().availableProcessors()    );
        buffer=new NewsBuffer();
    }

    @Override
    public void run() {
        //消费任务
        NewsWriterTask writerTask=new NewsWriterTask(buffer);
        Thread t=new Thread(   writerTask );
        t.start();

        //读取 sources.txt中的RSS源的地址， 有几个源，就启动几个生产任务.
        Path file= Paths.get(    sourcesPath );
        try(   BufferedReader reader=new BufferedReader(   new FileReader(  file.toFile()  )   )  ){
            String line=null;
            while(  (line=reader.readLine())!=null ){
                String[] strs=line.split(";");
                if(   strs!=null && strs.length==2) {
                    String rssName = strs[0];
                    String url = strs[1];
                    //创建生产者的任务
                    NewsProductTask productTask=new NewsProductTask(  rssName, url, buffer   );
                    this.executor.scheduleWithFixedDelay(    productTask, 0,  10, TimeUnit.MINUTES  );
                }
            }
        }catch(Exception ex){
            log.error(  ex );
        }



    }
}
